package com.examplemartin.jpademo.util;

import com.examplemartin.jpademo.pojo.po.MenuPO;
import com.examplemartin.jpademo.pojo.vo.MenuVO;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * 菜单工具类
 */
public class MenuUtil {

  /**
   * 获取顶级菜单
   * @param menulist
   * @return
   */
  public static List<MenuPO> getTopMenu(List<MenuPO> menulist){
    ArrayList<MenuPO> ret = new ArrayList<>();
    menulist.sort(new Comparator<MenuPO>() {
      @Override
      public int compare(MenuPO o1, MenuPO o2) {
        return o1.getPosition()-o2.getPosition();
      }
    });
    for (MenuPO menuPO : menulist) {
      if(menuPO.getId()!=1&&menuPO.getParent().getId()==1){
        ret.add(menuPO);
      }
    }

    return ret;
  }

  /**
   * 获取2级菜单
   * @param menulist
   * @return
   */
  public static List<MenuPO> getSecMenu(List<MenuPO> menulist){
    ArrayList<MenuPO> ret = new ArrayList<>();
    for (MenuPO menuPO : menulist) {
      if(menuPO.getId()!=1&&menuPO.getParent().getId()!=1){
        ret.add(menuPO);
      }
    }

    return ret;
  }

  /**
   * 菜单组装
   */
  public static List<MenuVO> assembleMenuList(List<MenuPO> menulist){
    List<MenuPO> topMenuList = getTopMenu(menulist);
    List<MenuPO> secMenuList = getSecMenu(menulist);
/**
 * private String menuname;
 *
 *   private String url;
 *   private String icon;
 *
 *   private Long parent_id;
 *
 *   private List<MenuVO> child;
 */
    ArrayList<MenuVO> ret = new ArrayList<>();
    for (MenuPO top : topMenuList) {
      MenuVO topVO = new MenuVO();
      // BeanUtils.copyProperties(top,topVO,"id","menuname","url","icon","parent_id");
      // 复制top类
      topVO.setId(top.getId());
      topVO.setMenuname(top.getMenuname());
      topVO.setUrl(top.getUrl());
      topVO.setIcon(top.getIcon());
      topVO.setParent_id(top.getParent().getId());
      topVO.setChild(new ArrayList<MenuVO>());

      for (MenuPO second : secMenuList) {
        if(second.getParent().getId()==topVO.getId()){

          MenuVO secondVO = new MenuVO();
          // BeanUtils.copyProperties(second,secondVO,"id","menuname","url","icon","parent_id");
          // 复制second类
          secondVO.setId(second.getId());
          secondVO.setMenuname(second.getMenuname());
          secondVO.setUrl(second.getUrl());
          secondVO.setIcon(second.getIcon());
          secondVO.setParent_id(second.getParent().getId());

          topVO.getChild().add(secondVO);

        }
      }
      ret.add(topVO);
    }
    return  ret;
  }


}
